package template

import (
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/dao/template"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
)

type operateTemplateParms struct {
	Id       int64 `form:"id"`
	CurPage  int   `form:"cur_page"`
	PageSize int   `form:"page_size"`
}

type templateParms struct {
	Id      int64  `form:"id"`
	Content string `form:"content" binding:"required"`
	Remarks string `form:"remark" binding:"required"`
}

func GetTemplate(c *gin.Context) {
	reqParam := operateTemplateParms{}
	if err := c.BindWith(&reqParam, binding.Form); err != nil {
		global.Log.Sugar().Error("参数错误", err)
		c.JSON(http.StatusOK, model.Fail("参数错误"))
		return
	}
	if reqParam.PageSize < 0 || reqParam.CurPage < 0 {
		global.Log.Sugar().Error("页码值非法")
		c.JSON(http.StatusOK, model.Fail("页码值非法，只可为正数"))
		return
	}
	count, listValue, err := template.GetTemplate(reqParam.Id, reqParam.CurPage, reqParam.PageSize)

	if err != nil {
		global.Log.Sugar().Error("获取模板失败", err)
		c.JSON(http.StatusOK, err)
		return
	}
	c.JSON(http.StatusOK, model.SuccessGrid(count, listValue))
}

func PutTemplate(c *gin.Context) {
	reqParam := templateParms{}
	if err := c.BindWith(&reqParam, binding.Form); err != nil {
		global.Log.Sugar().Error("参数错误", err)
		c.JSON(http.StatusOK, model.Fail("参数错误"))
		return
	}
	temp := template.Template{}
	temp.Id = reqParam.Id
	temp.Content = reqParam.Content
	temp.Remarks = reqParam.Remarks
	err := template.PutTemplate(&temp)
	if err != nil {
		global.Log.Sugar().Error("插入模板失败", err)
		c.JSON(http.StatusOK, model.Fail("操作失败"))
		return
	}
	c.JSON(http.StatusOK, model.Success("操作成功"))
}
func DelTemplate(c *gin.Context) {
	reqParam := operateTemplateParms{}
	if err := c.BindWith(&reqParam, binding.Form); err != nil {
		global.Log.Sugar().Error("参数错误", err)
		c.JSON(http.StatusOK, model.Fail("参数错误"))
		return
	}
	if err := template.DelTemplate(reqParam.Id); err != nil {
		global.Log.Sugar().Error("插入模板失败", err)
		c.JSON(http.StatusOK, err)
		return
	}
	c.JSON(http.StatusOK, model.Success("操作成功"))
}
